package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {
    public static final Long CACHE_NULL_TTL = 2L;
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set (String key, Object value, Long Time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),Time,unit);
    }
    //逻辑过期
    public void setWithLocalExpire(String key, Object value, Long Time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(Time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
    //缓存null解决穿透
    public <R,ID> R queryWithPassThrough(String key, Class<R> type, ID id, Function<ID,R> dbFunction,Long Time, TimeUnit unit){
        String cacheJson = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(cacheJson)){
            return JSONUtil.toBean(cacheJson,type);
        }
        if(cacheJson!=null){
            return null;
        }
        R r = dbFunction.apply(id);
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        this.set(key,r,Time,unit);
        return r;
    }

    //分布式锁解决击穿
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public <R,ID> R queryWithLogicalExpire(String key,Class<R> type,Function<ID,R> dbFunction,ID id,Long Time,TimeUnit unit){
        String cacheJson = stringRedisTemplate.opsForValue().get(key);
        if (cacheJson == null) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(cacheJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        LocalDateTime expireTime = redisData.getExpireTime();
        R r = JSONUtil.toBean(data, type);
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }
        Boolean isLock = tryLock("lock:" + key);
        if (isLock) {
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R r1 =dbFunction.apply(id);
                    this.setWithLocalExpire(key,r1,Time,unit);
                }finally {
                    nuLock("lock:"+key);
                }

            });
        }
       return r;

    }
    private Boolean tryLock(String key){
        Boolean faly = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10L, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(faly);
    }
    private void nuLock(String key){
        stringRedisTemplate.delete(key);
    }


}
